<template>
  <PageContainer>
    <view class="container">
      <Header title="意向详情" />
      <!-- 申请状态 -->
      <StatusView
        :status="applyStatus"
        :title="title"
        :bo-info-id="boInfoId"
        :bo-type="boType"
        :application-time="applicationTime"
        :approval-remark="approvalRemark"
      />
      <!-- 发起人 -->
      <PersonnelInfo
        v-if="routeOptions?.type === 'received' && boUserInfoVo"
        v-bind="boUserInfoVo"
        title="意向发起人信息"
        :custom-phone="true"
        @custom-make-phone-call="openPopup()"
      />
      <!-- 聊天 -->
      <view v-if="boUserInfoVo?.imUserId" class="disFlxAC pa-16 mb-12 bg-white" @click="toImView">
        <view class="disFlxAC flex-1">
          <text class="ali-icon mr-8 fz-24">&#xe6d0;</text>
          <text class="fz-16 font-bold default-color">在线沟通</text>
        </view>
        <view v-if="boUserInfoVo.msgNum" class="msg-num mx-10 w-24 h-24 br-12 fz-12 disFlxCC">
          <text>{{ boUserInfoVo.msgNum > 99 ? '99+' : boUserInfoVo.msgNum }}</text>
        </view>
        <text class="ali-icon fz-16" style="color: #969799">&#xe67b;</text>
      </view>
      <!-- 撮合 -->
      <MatchView
        :bo-info-id="boInfoId"
        :type="routeOptions?.type"
        :apply-record-id="routeOptions?.id"
        :data="boUserApplySecreariatVo"
        :status="applyStatus"
      />
      <!-- 表单 -->
      <view class="pa-16">
        <view class="fz-16 default-color font-bold mb-12"><text>意向详情</text></view>
      </view>
      <view class="br-8 overflow-hidden bg-white">
        <BasicsForm :schemas="schemas" @register="register" />
      </view>

      <TButtonGroup v-if="getShowButton" show-background>
        <TButton
          v-if="applyStatus !== IntentionStatusEnum.hold"
          text="搁置"
          class="gutter-btn"
          :customStyle="{
            border: ' 2rpx solid  #CCCCC8',
          }"
          custom-class="h-44 linh-44 br-22"
          @click="handleHold"
        />
        <TButton
          text="不合适"
          class="gutter-btn"
          :customStyle="{
            border: ' 2rpx solid  #CCCCC8',
          }"
          custom-class="h-44 linh-44 br-22"
          @click="modalVisible = true"
        />
        <TButton
          text="已联系"
          type="primary"
          class="gutter-btn"
          custom-class="h-44 linh-44 br-22"
          @click="handleSuccess"
        />
      </TButtonGroup>
      <TButtonGroup
        v-if="routeOptions?.type === 'send' && applyStatus === IntentionStatusEnum.unsuitable"
        show-background
      >
        <TButton
          text="重新发起意向"
          type="primary"
          class="gutter-btn"
          custom-class="h-44 linh-44 br-22"
          @click="toSupplyDemandDetails"
        />
      </TButtonGroup>

      <ShowModal
        v-model="modalVisible"
        title="不合适"
        content-width="100%"
        cancel-text="取消"
        confirm-text="确认不合适"
        confirm-color="#2878FF"
        :is-mask-click="false"
        :confirm-auto-close="false"
        @confirm="() => handleConfirm(IntentionStatusEnum.unsuitable)"
      >
        <template #content>
          <view class="pa-20" style="width: 100%">
            <view class="fz-14 mb-16" style="color: #969799">
              <text>告知一下对方不合适的原因吧</text>
            </view>
            <view style="background-color: #f2f3f5">
              <UniEasyinput
                v-model="reasonsVal"
                type="textarea"
                placeholder="很抱歉，经过我们评估，暂不合适合作"
              />
            </view>
          </view>
        </template>
      </ShowModal>
      <ScrollTop :bottom="220" />
    </view>
  </PageContainer>

  <UniPopup ref="phoneCallPopup">
    <view class="phoneCall-info">
      <text class="title">联系TA</text>
      <text class="desc">可通过以下电话联系TA</text>
      <view class="phoneCall-info_item_box">
        <template v-for="v in phoneNumberList" :key="v.id">
          <view class="phoneCall-info_item">
            <text class="phoneCall-info_phone font-bold" @click="callPhone(v)">
              {{ v }}
            </text>
            <view class="disFlxJC">
              <TButton
                text="复制"
                class="gutter-btn"
                :customStyle="{
                  border: ' 2rpx solid  #C8CACC',
                }"
                custom-class="h-24 linh-24 br-12"
                @click="handleCopy(v)"
              />
              <TButton
                text="拨打"
                class="gutter-btn"
                :customStyle="{
                  border: ' 2rpx solid  #C8CACC',
                }"
                custom-class="h-24 linh-24 br-12 ml-8"
                @click="callPhone(v)"
              />
            </view>
          </view>
        </template>
      </view>
      <view class="btn" @click="closePopup()">关闭</view>
    </view>
  </UniPopup>
</template>

<script lang="ts" setup>
  /* intentionDetails 意向详情 */
  import Header from '@/components/Header/index.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import { navigateTo, onLoad } from '@/router';
  import { BoTypeEnum, IntentionStatusEnum } from '@/enums/businessOpportunitiesEnum';
  import StatusView from './components/StatusView.vue';
  import PersonnelInfo from '../components/PersonnelInfo.vue';
  import MatchView from './components/MatchView.vue';
  import BasicsForm from '@/components/Form/BasicsForm.vue';
  import { useForm, type FormSchema } from '@/components/Form';
  import { computed, getCurrentInstance, ref } from 'vue';
  import { forEach, isArray } from 'lodash-es';
  import { localDataMapping } from '@/components/Form/hooks/useForm';
  import ScrollTop from '@/components/ScrollTop/index.vue';
  import { onPageScroll, onPullDownRefresh, onShow } from '@dcloudio/uni-app';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import ShowModal from '@/components/ShowModal/index.vue';
  import UniEasyinput from '@/uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue';
  import type { IntentionDetails } from '@/router/types/modules';
  import {
    intentionApplyRecordDetails,
    receiveApplyRecordReview,
  } from '@/api/businessOpportunities';
  import { Toast } from '@/utils';
  import type { IIntentionApplyRecordDetailsResult } from '@/api/businessOpportunities/type';
  import UniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
  import { UniEmitNameEnum } from '@/enums/uniEmitEnum';

  const schemas = ref<FormSchema[]>([]);
  const [register, {}] = useForm({
    labelAlign: 'left',
    labelPosition: 'top',
    validateTrigger: 'bind',
  });

  const routeOptions = ref<IntentionDetails>();
  const title = ref<string>('');
  const boInfoId = ref<number>();
  const boType = ref<BoTypeEnum>();
  const applicationTime = ref<string>();
  const applyStatus = ref<IntentionStatusEnum>();
  const boUserInfoVo = ref<IIntentionApplyRecordDetailsResult['boUserInfoVo']>();
  const boUserApplySecreariatVo =
    ref<IIntentionApplyRecordDetailsResult['boUserApplySecreariatVo']>();
  const approvalRemark = ref<string>();

  const phoneNumberList = ref<string[]>([]);

  onLoad<'intentionDetails'>(async (op) => {
    routeOptions.value = op;
    const res = await getData();
    if (res?.formItemList) {
      const list: FormSchema[] = [];
      forEach(res.formItemList, (v) => {
        const answer = v.formUserItemAnswerList;
        const defaultValue = isArray(answer) ? answer[answer.length - 1].content : '';
        list.push({
          field: v.id.toString(),
          label: v.showName,
          component: v.itemType,
          defaultValue,
          required: !!v.isRequired,
          dynamicDisabled: true,
          componentProps: {
            placeholder: v.value,
            localdata: localDataMapping(v.customFormItemAnswerList || [], {
              label: 'words',
              value: 'id',
            }),
          },
        });
      });

      schemas.value = list;
      schemas.value.forEach((v) => {
        if (v.component === 'InputPhone' && v.defaultValue) {
          const val = JSON.parse(v.defaultValue);
          val[0] && phoneNumberList.value.push(val[0]);
        }
      });
    }
  });

  const getShowButton = computed(() => {
    if (routeOptions.value?.type === 'received') {
      return (
        applyStatus.value === IntentionStatusEnum.pending ||
        applyStatus.value === IntentionStatusEnum.hold
      );
    }
    return false;
  });

  onShow(() => {
    if (routeOptions.value && boInfoId.value) getData();
  });

  async function getData() {
    if (!routeOptions.value) return;
    const res = await intentionApplyRecordDetails({
      type: routeOptions.value.type,
      id: routeOptions.value.id,
    });
    boInfoId.value = res.boInfoId;
    title.value = res.title;
    boType.value = res.boType;
    applicationTime.value = res.createTime;
    applyStatus.value = res.applyStatus;
    boUserInfoVo.value = res.boUserInfoVo;
    boUserApplySecreariatVo.value = res.boUserApplySecreariatVo;
    approvalRemark.value = res.approvalRemark;

    uni.stopPullDownRefresh();

    return res;
  }

  const _this = getCurrentInstance();
  const openPopup = (direction: string = 'center') => {
    (_this?.refs['phoneCallPopup'] as any).open(direction);
  };

  const closePopup = (direction: string = 'center') => {
    (_this?.refs['phoneCallPopup'] as any).close(direction);
  };

  /** 拨打电话 */
  function callPhone(phoneNumber: string) {
    uni.makePhoneCall({ phoneNumber, fail: (err) => console.log(err) });
  }
  /** 复制电话 */
  function handleCopy(phoneNumber: string) {
    uni.setClipboardData({
      data: phoneNumber,
      showToast: true,
    });
  }

  /** 搁置 */
  function handleHold() {
    uni.showModal({
      title: '确认搁置意向？',
      content: '搁置意向将不再提醒本意向待办，也不会通知意向发送者。',
      cancelColor: '#969799',
      cancelText: '取消',
      confirmColor: '#2878FF',
      confirmText: '确定搁置',
      success: (res) => {
        res.confirm && handleConfirm(IntentionStatusEnum.hold);
      },
    });
  }

  /** 确认联系 */
  function handleSuccess() {
    uni.showModal({
      title: '确认已联系成功？',
      content: '确认您与意向发送者已联系上？',
      cancelColor: '#969799',
      cancelText: '取消',
      confirmColor: '#2878FF',
      confirmText: '确认',
      success: (res) => {
        res.confirm && handleConfirm(IntentionStatusEnum.success);
      },
      fail: (err) => console.log(err),
    });
  }

  const modalVisible = ref(false);
  const reasonsVal = ref('');

  /** 意向处理 */
  function handleConfirm(approvalStatus: IntentionStatusEnum) {
    if (!routeOptions.value) return;
    receiveApplyRecordReview({
      id: routeOptions.value?.id,
      approvalStatus,
      approvalRemark: approvalStatus === IntentionStatusEnum.unsuitable ? reasonsVal.value : '',
    }).then(() => {
      reasonsVal.value = '';
      modalVisible.value = false;
      getData();
      Toast('操作成功');
      uni.$emit(UniEmitNameEnum.REFRESHPREVIOUSPAGE);
    });
  }

  function toImView() {
    if (!boUserInfoVo.value?.imUserId) return;
    navigateTo({
      name: 'TUIChat',
      options: {
        conversationID: `C2C${boUserInfoVo.value?.imUserId}`,
      },
    });
  }

  function toSupplyDemandDetails() {
    navigateTo({ name: 'supplyDemandDetails', options: { id: boInfoId.value! } });
  }

  onPageScroll(() => {});

  onPullDownRefresh(() => getData());
</script>

<style lang="scss" scoped>
  .msg-num {
    background-color: #ea5e0e;
    color: #fff;
  }

  .phoneCall-info {
    box-sizing: border-box;
    width: 622rpx;
    border-radius: 32rpx;
    background-color: #fff;
    padding: 48rpx 48rpx 32rpx 48rpx;
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: space-around;
    .title {
      color: #333;
      text-align: center;
      font-size: 32rpx;
      font-weight: 400;
      line-height: 48rpx;
      font-weight: bold;
    }
    .desc {
      color: #333;
      text-align: center;
      font-size: 28rpx;
      font-weight: 400;
      line-height: 40rpx;
      margin: 24rpx 0 32rpx 0;
    }
    .phoneCall-info_item_box {
      width: 100%;
      max-height: 400rpx;
      overflow-y: scroll;

      .phoneCall-info_item {
        width: 100%;
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 32rpx;
        color: #333;
        padding: 24rpx 20rpx;
        background-color: #f7f8fa;
        margin-top: 20rpx;
        border-radius: 16rpx;
      }
      .phoneCall-info_phone {
        color: #4a75ff;
      }
    }

    .btn {
      margin-top: 32rpx;
      box-sizing: border-box;
      display: flex;
      width: 100%;
      height: 72rpx;
      padding: 8px 0px;
      justify-content: center;
      align-items: center;
      border-radius: 32rpx;
      background: #2878ff;
      color: #fff;
      font-size: 28rpx;
    }
  }
</style>
